//
//  YJDeviceManager.swift
//  KCTBluetoothSDKDemo
//
//  Created by caofuqing on 2022/9/14.
//  Copyright © 2022 Qinsz. All rights reserved.
//

import Foundation

class YJDeviceManager: NSObject {
    static let share = YJDeviceManager()
    /// 外设数组
    var peripherals = Array<CBPeripheral>.init()
    private let shell = KCTSingleBLEShell.sharedInstance
    /// 通过注释，打开/关闭MTK模块
    private var mtkShell:KCTMTKShell? = KCTMTKShell.share
    private var mtkConnectionTimer:Timer?
    private override init() {
        super.init()
        shell.delegate = self
        shell.searchDelegate = self
        mtkShell?.delegate = self
    }
    
    /// 1.开启搜索设备 是否通过服务UUID进行过滤  filter=true 过滤
    public func startScanWithFilter(filter:Bool) {
        peripherals.removeAll()
        peripherals.append(contentsOf: shell.retrievePairedPeripherals())
        shell.startScan(withServicesFilter: filter)
        if mtkShell?.shakedHands == false{
            // 容错处理: 已经握手时，调用mtk的搜索方法会导致无法发送消息，且无法重新握手（只有在设置中忽略设备后才能恢复正常）
            mtkShell?.startScan()
        }
    }
    
    /// 2.停止搜索
    public func stopScan() {
        shell.stopScan()
        mtkShell?.stopScan()
    }
    
    /// 3.连接蓝牙设备
    public func connection() {
        guard let peripheral = peripherals.first else {
            SVProgressHUD.show(withStatus: "请稍后，正在搜索中...")
            return
        }
        shell.stopScan()
        SVProgressHUD.show(withStatus: "正在连接...")
        if let name = peripheral.name {
            if name.contains("SW330") {
                peripheral.type = .Wear
            }
        }
        if peripheral.type == .Wear {
            if ( mtkShell != nil){
                if let t = mtkConnectionTimer {
                    t.invalidate()
                }
                mtkConnectionTimer = Timer.init(timeInterval: 30.0, target: self, selector: #selector(mtkConnectionTimeout(timer:)), userInfo: nil, repeats: false)
                RunLoop.main.add(mtkConnectionTimer!, forMode: .default)
                if mtkShell?.tempPeripheral?.state == .connecting || mtkShell?.tempPeripheral?.state == .connected{
                    mtkShell?.cancelConnection()
                }
                DispatchQueue.main.asyncAfter(deadline: .now()+3, execute:
                {
                    self.mtkShell?.connect(peripheral: peripheral)
                })

            }else{
                SVProgressHUD.showInfo(withStatus: "没有初始化MTKShell")
            }
        }else if peripheral.type == .Bracelet || peripheral.type == .Android{
            var shakeHande = true
            mtkShell?.stopScan()
            if let dfu = peripheral.name?.contains("DfuTarg"), dfu == true {
                shakeHande = false
            }
            shell.connect(peripheral: peripheral, withShakehands: shakeHande)
        }else{
            SVProgressHUD.showInfo(withStatus: "未知的设备类型")
        }
    }
    /// MTK连接超时
    @objc func mtkConnectionTimeout(timer:Timer) {
        IPrint("连接MTK设备超时了")
        // 防止超时后的连接成功的回调
        mtkShell?.cancelConnection()
        SVProgressHUD.showInfo(withStatus: "连接MTK设备超时了")
    }

}
extension YJDeviceManager: KCTSingleBLEShellSearchDelegate {
    func singleBLEShell(shell: KCTSingleBLEShell, didDiscover peripheral: CBPeripheral) {
        // 将发现的设备通过通知POST出去，需要的页面自行监听该通知获取搜索结果
        NotificationCenter.default.post(name: Notification_DiscoveredPeripheral, object: peripheral)
        
        if !peripherals.contains(peripheral) {
            peripherals.append(peripheral)
        }
        print("搜索到了数据11111111111111111111111111111111111111")
        print(peripheral)
        print("搜索到了数据222222222222222222222222222222222222222")
        var dic = ["name":peripheral.name]
        SwiftYjHealthPlugin.shareInstance.sendToFlutter(dic.toJsonString())
    }
}
extension YJDeviceManager: KCTMTKShellDelegate {
    func mtkShellShakedHands(shell: KCTMTKShell) {
        IPrint("FirstVC:MTK握手成功")
        mtkConnectionTimer?.invalidate()
        shell.stopScan()
        SVProgressHUD.showSuccess(withStatus: "MTK握手成功")
    }
    
    func mtkShell(shell: KCTMTKShell, changeState state: Int32) {
        IPrint("FirstVC:MTK蓝牙状态改变:\(state)")
    }
    
    func mtkShell(shell: KCTMTKShell, received cmd: String, message: NSObject?, error: KCTError?) {
        var des:Any?
        if let obj = message,let js =  obj.yy_modelToJSONObject(){
            des = js
        }else{
            des = message
        }
        IPrint("MTKRawCmdVC:MTK收到解析后的消息:\ncmd=\(cmd)\nerror=\(error?.description ?? "")\nmessage=\(des ?? "")")
    }
    
    func mtkShell(scanPeripheral: CBPeripheral) {

    }
    
    
}

extension YJDeviceManager: KCTSingleBLEShellDelegate {
    func singleBLEShell(shell: KCTSingleBLEShell, didUpdateState state: CBManagerState) {

    }
    
    func singleBLEShell(shell: KCTSingleBLEShell, failedToConnect peripheral: CBPeripheral, error: KCTError) {
        IPrint("链接失败:\(error)")
        
        SVProgressHUD.showError(withStatus: "链接失败:\(error)")
        
        // 将断开连接的消息POST出去，需要的页面自行监听该通知进行处理
        NotificationCenter.default.post(name: Notification_DisconnectBLEDevice, object: peripheral, userInfo: ["error":error])
    }
    
    func singleBLEShell(shell: KCTSingleBLEShell, successToConnect peripheral: CBPeripheral, handShaked: Bool) {
        IPrint("链接成功")
        
        var dic = ["name":peripheral.name]
        SwiftYjHealthPlugin.shareInstance.sendToFlutter(dic.toJsonString())
        
        NotificationCenter.default.post(name: Notification_ConnectBLEDevice, object: peripheral)
        
        if handShaked == true {
            // 握手连接的情况下，才自动进入BLECmdVC
            SVProgressHUD.showSuccess(withStatus: "BLE握手成功")
        }else{
            // 未握手的连接
            SVProgressHUD.showSuccess(withStatus: "连接成功(未握手)")
        }
    }
    
    func singleBLEShell(shell: KCTSingleBLEShell, serviceCharacteristicReceivedRawData rawData: Data) {
        let data = NSData.init(data: rawData)
        IPrint("收到原始蓝牙数据:\(data)")
    }
    
    func singleBLEShell(shell: KCTSingleBLEShell, recievedActiveMsg msgModel: NSObject) {
        if let json = msgModel.yy_modelToJSONObject(){
            IPrint("收到设备主动发来的消息:\(json)")
        }else{
            IPrint("收到设备主动发来的消息:\(msgModel)")
        }
    }
    
    
}


